/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.institution.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.institution.approval.ConformanceAuditService;
import com.koron.institution.bean.ConformanceAssessment;
import com.koron.institution.bean.ConformanceAssessmentHistory;
import com.koron.institution.bean.LawCond;
import com.koron.institution.bean.LawCorp;
import com.koron.institution.mapper.ConformanceAssessmentHistoryMapper;
import com.koron.institution.mapper.ConformanceAssessmentMapper;
import com.koron.institution.mapper.LawCorpMapper;
import com.koron.institution.service.api.ConformanceService;
import com.koron.institution.uitls.BaseEntityUtil;
import com.koron.institution.uitls.BusinessCode;
import com.koron.safetytask.domain.JobsTasks;
import com.koron.safetytask.mapper.JobsTasksMapper;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.*;

@Service
@PropertySource("classpath:institution.properties")
public class ConformanceServiceImpl implements ConformanceService, InitializingBean, AfterApprovalService {

    private final static  Logger logger = LoggerFactory.getLogger(Logger.class);

    @Autowired
    private FlowManagement flowManagement;

//    @Value("${assessment_confirm}")
//    private String assessmentConfirm;


//    @Value("${conformance_add_template_key}")
//    private String conformanceAddTemplateKey;
//
//    @Value("${conformance_edit_template_key}")
//    private String conformanceEditTemplateKey;
//
//    @Value("${conformance_discard_template_key}")
//    private String conformanceDiscardTemplateKey;

    @Value("${conformance_add_confirm}")
    private String conformanceAddConfirm;

    @Value("${conformance_edit_confirm}")
    private String conformanceEditConfirm;

    @Value("${conformance_discard_confirm}")
    private String conformanceDiscardConfirm;

    @Value("${assessment_conformance_template_key}")
    private String assessmentConformanceTemplateKey;

    @Override
    public MessageBean<?> getConformanceList(String corpCode, Integer conformanceYear, String institutionName, Integer page, Integer pageSize, Integer state, StaffBean user) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            ConformanceAssessmentMapper mapper = factory.getMapper(ConformanceAssessmentMapper.class);
            if (StringUtils.isBlank(corpCode)) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT_CORPCODE.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_CORPCODE.getDescription());
                return msg;
            }
            Integer start = null;
            if (page != null && page > 0 && pageSize != null && pageSize > 0) {
                start = (page - 1) * pageSize;
            }
            List<ConformanceAssessment> list = mapper.selectByCond(corpCode, conformanceYear, institutionName, state, start, pageSize, null);
            int total = mapper.selectTotalByCond(corpCode, conformanceYear, institutionName, state);
            DataBean<ConformanceAssessment> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setTotalNumber(total);
            dataBean.setPageNo(page);
            dataBean.setPageSize(pageSize);
            dataBean.setTotalPage((pageSize == null || pageSize == 0) ? 0 : total / pageSize);
            msg.setData(dataBean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    @Override
    public MessageBean<?> getConformanceDraftList(String corpCode, Integer conformanceYear, String institutionName, Integer page, Integer pageSize, Integer state, StaffBean user) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            ConformanceAssessmentMapper mapper = factory.getMapper(ConformanceAssessmentMapper.class);
            if (StringUtils.isBlank(corpCode)) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT_CORPCODE.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_CORPCODE.getDescription());
                return msg;
            }
            Integer start = null;
            if (page != null && page > 0 && pageSize != null && pageSize > 0) {
                start = (page - 1) * pageSize;
            }
            List<ConformanceAssessment> list = mapper.queryDraftList(corpCode, conformanceYear, institutionName, start, pageSize);
            int total = mapper.queryDraftListTotal(corpCode, conformanceYear, institutionName);
            DataBean<ConformanceAssessment> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setTotalNumber(total);
            dataBean.setPageNo(page);
            dataBean.setPageSize(pageSize);
            dataBean.setTotalPage((pageSize == null || pageSize == 0) ? 0 : total / pageSize);
            msg.setData(dataBean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }


    @Override
    public MessageBean<?> saveOrCommit(StaffBean user, String corpCode, Integer operationType, String conformanceAssessmentListStr, String approverCodeListStr, String jobsTaskId, Integer conformanceYear) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        SessionFactory factory = new SessionFactory();
        List<String> idList = new ArrayList<>();
        try {
            List<String> approverCodeList = null;
            ConformanceAssessmentHistoryMapper historyMapper = factory.getMapper(ConformanceAssessmentHistoryMapper.class);
            ConformanceAssessmentMapper mapper = factory.getMapper(ConformanceAssessmentMapper.class);

            if (null == operationType) {
                msg.setCode(BusinessCode.ASSESSMENT__EMPTY_OPERATIONTYPE.getCode());
                msg.setDescription(BusinessCode.ASSESSMENT__EMPTY_OPERATIONTYPE.getDescription());
                factory.close();
                return msg;
            }
            if (1 != operationType && 0 != operationType) {
                msg.setCode(BusinessCode.ASSESSMENT_ILEAGEL_OPERATIONTYPE.getCode());
                msg.setDescription(BusinessCode.ASSESSMENT_ILEAGEL_OPERATIONTYPE.getDescription());
                factory.close();
                return msg;
            }
            if (StringUtils.isBlank(conformanceAssessmentListStr)) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT_CONFORMANCE.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_CONFORMANCE.getDescription());
                return msg;
            }
            List<ConformanceAssessment> conformanceAssessmentList = JSONObject.parseArray(conformanceAssessmentListStr, ConformanceAssessment.class);
            //校验
            checkConformanceAssessment(corpCode, conformanceAssessmentList, msg);
            if (msg.getCode() != 0) {
                factory.close();
                return msg;
            }
            for (ConformanceAssessment conformanceAssessment : conformanceAssessmentList) {
                //新增评估要判断是否重复评估
                //判断该制度是否已评估修订不能重复添加
                List<ConformanceAssessment> conformanceAssessments = mapper.queryListByCode(corpCode, conformanceAssessment.getConformanceYear(), conformanceAssessment.getInstitutionCode());
                if (conformanceAssessments != null && !conformanceAssessments.isEmpty() && conformanceAssessments.stream().anyMatch(conformance -> !conformance.getId().equals(conformanceAssessment.getId()))) {
                    msg.setCode(24101);
                    msg.setDescription("制度已经存在合规评价,请勿重复添加!");
                    factory.close(false);
                    return msg;
                }

                if (operationType == 0) {
                    conformanceAssessment.setState(5);
                } else {

                    conformanceAssessment.setState(1);
                }
                //判断是否新增草稿
                if (StringUtils.isBlank(conformanceAssessment.getId())) {
                    //新增草稿
                    BaseEntityUtil.setAddBaseProperties(conformanceAssessment, user);
                    mapper.insert(conformanceAssessment);
                } else {
                    //修改草稿
                    BaseEntityUtil.setUpdateBaseProperties(conformanceAssessment, user);
                    mapper.updateByPrimaryKeySelective(conformanceAssessment);
                }
                if (operationType == 1) {
                    ConformanceAssessmentHistory history = new ConformanceAssessmentHistory();
                    BeanUtils.copyProperties(conformanceAssessment, history);
                    history.setHistoryFlag(0);
                    history.setId(DefaultIdGenerator.getInstance().generateLongId());
                    history.setOldId(conformanceAssessment.getId());
                    historyMapper.insert(history);
                    idList.add(history.getId());
                }
            }
            if (operationType == 1) {
                if (StringUtils.isBlank(approverCodeListStr)) {
                    msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
                    msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
                    factory.close(false);
                    return msg;
                }
                approverCodeList = JSONObject.parseArray(approverCodeListStr, String.class);
                if (approverCodeList == null || approverCodeList.isEmpty()) {
                    msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
                    msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
                    factory.close(false);
                    return msg;
                }
                // 构造audit
                Audit audit = new Audit();
                Date now = new Date();
                audit.setId(DefaultIdGenerator.getInstance().generateLongId());
                audit.setUpdateUser(user.getName());
                audit.setUpdateTime(now);
                audit.setAddUser(user.getName());
                audit.setAddTime(now);
                audit.setFlowType(1);
                audit.setOperation(1);
                audit.setTarget(ConformanceAuditService.class.getName());
                audit.setFlowName(conformanceAddConfirm);
                audit.setTitle(conformanceAddConfirm);
                audit.setCorpCode(corpCode);
                audit.setInitiatorCode(user.getCode());
                audit.setDescription("合规评价提交审批");
                audit.setState(1);
                audit.setTemplateKey(assessmentConformanceTemplateKey);
                audit.setBusinessIds(new Gson().toJson(idList));
                //更新任务状态
                if (StringUtils.isNotBlank(jobsTaskId)) {
                    JobsTasksMapper jobsTasksMapper = factory.getMapper(JobsTasksMapper.class);
                    JobsTasks jobsTasks = jobsTasksMapper.queryById(jobsTaskId);
                    if (jobsTasks != null) {
                        jobsTasks.setBusinessId(new Gson().toJson(idList));
                        Date commitDate = new Date();
                        jobsTasks.setFstatusflag(1);
                        jobsTasks.setState(3);
                        jobsTasks.setCompletedTime(commitDate);
                        jobsTasksMapper.completed(jobsTasks);
                        audit.setOtherBusinessIds(jobsTaskId);
                    }
                }
                Map<String, Object> businessMap = new HashMap<>();
                StringBuilder codes = new StringBuilder();
                for (String code : approverCodeList) {
                    codes.append("1-").append(code.split("_")[0]).append(",");
                }
                businessMap.put("approver", codes.toString().substring(0, codes.lastIndexOf(",")));
                if (!flowManagement.initFlow(user, audit, businessMap)) {
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("提交合规评价失败");
                } else {
                    factory.close();
                    msg.setCode(BusinessCode.SUCCESS.getCode());
                    msg.setDescription("提交合规评价成功");
                }
            }
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public Map<String, Object> queryExportData(String title, String fileCode, String recordCode, String version, StaffBean user, String corpCode, String corpName, Integer conformanceYear) {
        Map<String, Object> map = new HashMap<>();
        try (SessionFactory factory = new SessionFactory()) {
            ConformanceAssessmentMapper mapper = factory.getMapper(ConformanceAssessmentMapper.class);
            List<ConformanceAssessment> list = mapper.selectByCond(corpCode, conformanceYear, null, null, null, null, 1);
            map.put("data", list);
            map.put("title", title);
            map.put("fileCode", fileCode);
            map.put("recordCode", recordCode);
            map.put("version", version);
            map.put("corpName", corpName);
            map.put("userName", user == null ? "" : user.getName());
            map.put("makeDate", new Date());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
        return map;
    }

    @Override
    public MessageBean<?> getProcessData(String ids) {
        MessageBean<List> msg = MessageBean.create(0, "success", List.class);
        try (SessionFactory factory = new SessionFactory();) {
            if (StringUtils.isNotBlank(ids)) {
                List<String> idList = JSONObject.parseArray(ids, String.class);
                if (idList != null && !idList.isEmpty()) {
                    ConformanceAssessmentHistoryMapper mapper = factory.getMapper(ConformanceAssessmentHistoryMapper.class);
                    List<ConformanceAssessmentHistory> list = mapper.queryListByIds(idList);
                    msg.setData(list);
                } else {
                    msg.setCode(BusinessCode.EMPTY_CONFORMANCE_ID.getCode());
                    msg.setDescription(BusinessCode.EMPTY_CONFORMANCE_ID.getDescription());
                    return msg;
                }
            } else {
                msg.setCode(BusinessCode.EMPTY_REVISE_ID.getCode());
                msg.setDescription(BusinessCode.EMPTY_REVISE_ID.getDescription());
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    @Override
    public MessageBean<?> getLawSelect(String corpCode, String name, Integer conformanceYear) {
        MessageBean<List> msg = MessageBean.create(0, "success", List.class);
        try (SessionFactory factory = new SessionFactory();) {
            LawCorpMapper mapper = factory.getMapper(LawCorpMapper.class);

            ConformanceAssessmentMapper conformanceMapper = factory.getMapper(ConformanceAssessmentMapper.class);
            ConformanceAssessmentHistoryMapper historyMapper = factory.getMapper(ConformanceAssessmentHistoryMapper.class);
            if (StringUtils.isBlank(corpCode)) {
                msg.setCode(24102);
                msg.setDescription("水司code不能为空");
                return msg;
            }
            LawCond cond = new LawCond();
            cond.setCorpCode(corpCode);
            cond.setFileName(name);
            List<LawCorp> list = mapper.getSelectList(cond);
            List<ConformanceAssessment> conformanceAssessmentList = conformanceMapper.queryListByYear(corpCode, conformanceYear);
            //获取审查状态下重复的
//            List<ConformanceAssessmentHistory> historyList = historyMapper.queryInProcessList(corpCode, conformanceYear);
            if (list != null && !list.isEmpty() && conformanceAssessmentList != null && !conformanceAssessmentList.isEmpty()) {
                List<LawCorp> distinctList = new ArrayList<>();
                for (LawCorp lawCorp : list) {
                    if (lawCorp == null) {
                        continue;
                    }
                    if (conformanceAssessmentList != null && conformanceAssessmentList.stream().anyMatch(conformanceAssessment -> {
                        if (conformanceAssessment != null) {
                            return lawCorp.getLawCode().equals(conformanceAssessment.getInstitutionCode());
                        } else {
                            return false;
                        }
                    })) {
                        continue;
                    }
                    distinctList.add(lawCorp);
                }
                list = distinctList;
            }
            msg.setData(list);
        } catch (Exception e) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    MessageBean<?> checkConformanceAssessment(String corpCode, List<ConformanceAssessment> conformanceAssessmentList, MessageBean<?> msg) {

        if (conformanceAssessmentList == null || conformanceAssessmentList.isEmpty()) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT_CONFORMANCE.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_CONFORMANCE.getDescription());
            return msg;
        }

        if (StringUtils.isBlank(corpCode)) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT_CORPCODE.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_CORPCODE.getDescription());
            return msg;
        }
        for (ConformanceAssessment conformanceAssessment : conformanceAssessmentList) {
            conformanceAssessment.setCorpCode(corpCode);
            if (conformanceAssessment == null) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT_CONFORMANCE.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_CONFORMANCE.getDescription());
                return msg;
            }

            if (conformanceAssessment.getConformanceFlag() == null) {
                msg.setCode(24101);
                msg.setDescription("是否符合不能为空");
                return msg;
            }
            if (StringUtils.isBlank(conformanceAssessment.getSuitDept())) {
                msg.setCode(24101);
                msg.setDescription("适用部门不能为空");
                return msg;
            }
            if (conformanceAssessment.getConformanceYear() == null) {
                msg.setCode(24101);
                msg.setDescription("合规评价年份不能为空");
                return msg;
            }

            if (StringUtils.isBlank(conformanceAssessment.getInstitutionCode())) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_CODE.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CODE.getDescription());
                return msg;
            }

            if (StringUtils.isBlank(conformanceAssessment.getCorpCode())) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getDescription());
                return msg;
            }
        }
        return msg;
    }

    MessageBean<?> checkConformanceAssessmentHistory(String corpCode, List<ConformanceAssessmentHistory> conformanceAssessmentHistoryList, MessageBean<?> msg, boolean isAdd) {

        if (conformanceAssessmentHistoryList == null || conformanceAssessmentHistoryList.isEmpty()) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT_CONFORMANCE.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_CONFORMANCE.getDescription());
            return msg;
        }

        if (StringUtils.isBlank(corpCode)) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT_CORPCODE.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_CORPCODE.getDescription());
            return msg;
        }
        for (ConformanceAssessmentHistory conformanceAssessmentHistory : conformanceAssessmentHistoryList) {
            conformanceAssessmentHistory.setCorpCode(corpCode);
            if (conformanceAssessmentHistory == null) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT_CONFORMANCE.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_CONFORMANCE.getDescription());
                return msg;
            }
            if (!isAdd) {
                if (StringUtils.isBlank(conformanceAssessmentHistory.getId())) {
                    msg.setCode(24101);
                    msg.setDescription("原评合规评价id不能为空");
                    return msg;
                } else {
                    conformanceAssessmentHistory.setOldId(conformanceAssessmentHistory.getId());
                }
            }
            if (conformanceAssessmentHistory.getConformanceFlag() == null) {
                msg.setCode(24101);
                msg.setDescription("是否符合不能为空");
                return msg;
            }
            if (StringUtils.isBlank(conformanceAssessmentHistory.getSuitDept())) {
                msg.setCode(24101);
                msg.setDescription("适用部门不能为空");
                return msg;
            }
            if (conformanceAssessmentHistory.getConformanceYear() == null) {
                msg.setCode(24101);
                msg.setDescription("合规评价年份不能为空");
                return msg;
            }

            if (StringUtils.isBlank(conformanceAssessmentHistory.getInstitutionCode())) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_CODE.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CODE.getDescription());
                return msg;
            }

            if (StringUtils.isBlank(conformanceAssessmentHistory.getCorpCode())) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_CORPCODE.getDescription());
                return msg;
            }

        }
        return msg;
    }

    MessageBean<?> checkDiscardConformanceAssessmentHistory(List<ConformanceAssessmentHistory> conformanceAssessmentHistoryList, MessageBean<?> msg) {

        if (conformanceAssessmentHistoryList == null || conformanceAssessmentHistoryList.isEmpty()) {
            msg.setCode(BusinessCode.EMPTY_ASSESSMENT_CONFORMANCE.getCode());
            msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_CONFORMANCE.getDescription());
            return msg;
        }
        List<ConformanceAssessmentHistory> list = new ArrayList<>();
        for (ConformanceAssessmentHistory conformanceAssessmentHistory : conformanceAssessmentHistoryList) {
            if (conformanceAssessmentHistory == null) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT_CONFORMANCE.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_CONFORMANCE.getDescription());
                return msg;
            }
            if (StringUtils.isBlank(conformanceAssessmentHistory.getId())) {
                msg.setCode(24101);
                msg.setDescription("原评合规评价id不能为空");
                return msg;
            }
        }
        return msg;
    }

    @Override
    public MessageBean<?> batchEdit(StaffBean user, String corpCode, String conformanceAssessmentHistoryListStr, String approverCodeListStr) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        SessionFactory factory = new SessionFactory();
        List<String> idList = new ArrayList<>();
        try {
            List<String> approverCodeList = null;
            ConformanceAssessmentHistoryMapper historyMapper = factory.getMapper(ConformanceAssessmentHistoryMapper.class);
            ConformanceAssessmentMapper mapper = factory.getMapper(ConformanceAssessmentMapper.class);
            if (StringUtils.isBlank(conformanceAssessmentHistoryListStr)) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT_CONFORMANCE.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_CONFORMANCE.getDescription());
                return msg;
            }
            List<ConformanceAssessmentHistory> conformanceAssessmentHistoryList = JSONObject.parseArray(conformanceAssessmentHistoryListStr, ConformanceAssessmentHistory.class);

            //校验
            checkConformanceAssessmentHistory(corpCode, conformanceAssessmentHistoryList, msg, false);
            if (msg.getCode() != 0) {
                factory.close();
                return msg;
            }
            for (ConformanceAssessmentHistory conformanceAssessmentHistory : conformanceAssessmentHistoryList) {
                ConformanceAssessment assessment = mapper.selectByPrimaryKey(conformanceAssessmentHistory.getOldId());
                if (assessment == null) {
                    msg.setCode(BusinessCode.OLD_RECORD_NOT_EXIST.getCode());
                    msg.setDescription(BusinessCode.OLD_RECORD_NOT_EXIST.getDescription());
                    factory.close(false);
                    return msg;
                }
                conformanceAssessmentHistory.setState(2);
                conformanceAssessmentHistory.setId(DefaultIdGenerator.getInstance().generateLongId());
                conformanceAssessmentHistory.setAddUser(assessment.getAddUser());
                conformanceAssessmentHistory.setAddUserName(assessment.getAddUserName());
                conformanceAssessmentHistory.setAddTime(assessment.getAddTime());
                BaseEntityUtil.setUpdateBaseProperties(conformanceAssessmentHistory, user);
                historyMapper.insert(conformanceAssessmentHistory);
                //修改原记录状态为审核中

                assessment.setState(2);
                mapper.updateByPrimaryKeySelective(assessment);
                idList.add(conformanceAssessmentHistory.getId());
            }

            if (StringUtils.isBlank(approverCodeListStr)) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
                factory.close(false);
                return msg;
            }
            approverCodeList = JSONObject.parseArray(approverCodeListStr, String.class);
            if (approverCodeList == null || approverCodeList.isEmpty()) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
                factory.close(false);
                return msg;
            }
            // 构造audit
            Audit audit = new Audit();
            Date now = new Date();
            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            audit.setUpdateUser(user.getName());
            audit.setUpdateTime(now);
            audit.setAddUser(user.getName());
            audit.setAddTime(now);
            audit.setFlowType(1);
            audit.setOperation(1);
            audit.setTarget(ConformanceServiceImpl.class.getName());
            audit.setFlowName(conformanceEditConfirm);
            audit.setTitle(conformanceEditConfirm);
            audit.setCorpCode(corpCode);
            audit.setInitiatorCode(user.getCode());
            audit.setDescription("编辑合规评价提交审批");
            audit.setState(1);
            audit.setTemplateKey(assessmentConformanceTemplateKey);
            audit.setBusinessIds(new Gson().toJson(idList));
            Map<String, Object> businessMap = new HashMap<>();
            StringBuilder codes = new StringBuilder();
            for (String code : approverCodeList) {
                codes.append("1-").append(code.split("_")[0]).append(",");
            }
            businessMap.put("approver", codes.toString().substring(0, codes.lastIndexOf(",")));
            if (!flowManagement.initFlow(user, audit, businessMap)) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("编辑提交合规评价失败");
            } else {
                factory.close();
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("编辑提交合规评价成功");
            }
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean<?> batchDiscard(StaffBean user, String corpCode, String conformanceAssessmentHistoryListStr, String approverCodeListStr) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        SessionFactory factory = new SessionFactory();
        List<String> idList = new ArrayList<>();
        try {
            List<String> approverCodeList = null;
            ConformanceAssessmentHistoryMapper historyMapper = factory.getMapper(ConformanceAssessmentHistoryMapper.class);
            ConformanceAssessmentMapper mapper = factory.getMapper(ConformanceAssessmentMapper.class);

            if (StringUtils.isBlank(conformanceAssessmentHistoryListStr)) {
                msg.setCode(BusinessCode.EMPTY_ASSESSMENT_CONFORMANCE.getCode());
                msg.setDescription(BusinessCode.EMPTY_ASSESSMENT_CONFORMANCE.getDescription());
                return msg;
            }
            List<ConformanceAssessmentHistory> conformanceAssessmentHistoryList = JSONObject.parseArray(conformanceAssessmentHistoryListStr, ConformanceAssessmentHistory.class);

            //校验
//            checkConformanceAssessmentHistory(corpCode, conformanceAssessmentHistoryList, msg, false);
            checkDiscardConformanceAssessmentHistory(conformanceAssessmentHistoryList, msg);
            if (msg.getCode() != 0) {
                factory.close();
                return msg;
            }
            for (ConformanceAssessmentHistory conformanceAssessmentHistory : conformanceAssessmentHistoryList) {
                ConformanceAssessment assessment = mapper.selectByPrimaryKey(conformanceAssessmentHistory.getId());
                if (assessment == null) {
                    msg.setCode(BusinessCode.OLD_RECORD_NOT_EXIST.getCode());
                    msg.setDescription(BusinessCode.OLD_RECORD_NOT_EXIST.getDescription());
                    factory.close(false);
                    return msg;
                }
                BeanUtils.copyProperties(assessment, conformanceAssessmentHistory);
                conformanceAssessmentHistory.setId(DefaultIdGenerator.getInstance().generateLongId());
                conformanceAssessmentHistory.setOldId(assessment.getId());
                conformanceAssessmentHistory.setState(3);
                BaseEntityUtil.setUpdateBaseProperties(conformanceAssessmentHistory, user);
                historyMapper.insert(conformanceAssessmentHistory);
                //修改原记录状态为审核中

                assessment.setState(3);
                mapper.updateByPrimaryKeySelective(assessment);
                idList.add(conformanceAssessmentHistory.getId());
            }

            if (StringUtils.isBlank(approverCodeListStr)) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
                factory.close(false);
                return msg;
            }
            approverCodeList = JSONObject.parseArray(approverCodeListStr, String.class);
            if (approverCodeList == null || approverCodeList.isEmpty()) {
                msg.setCode(BusinessCode.EMPTY_INSTITUTION_APPROVER.getCode());
                msg.setDescription(BusinessCode.EMPTY_INSTITUTION_APPROVER.getDescription());
                factory.close(false);
                return msg;
            }
            // 构造audit
            Audit audit = new Audit();
            Date now = new Date();
            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            audit.setUpdateUser(user.getName());
            audit.setUpdateTime(now);
            audit.setAddUser(user.getName());
            audit.setAddTime(now);
            audit.setFlowType(1);
            audit.setOperation(2);
            audit.setTarget(ConformanceServiceImpl.class.getName());
            audit.setFlowName(conformanceDiscardConfirm);
            audit.setTitle(conformanceDiscardConfirm);
            audit.setCorpCode(corpCode);
            audit.setInitiatorCode(user.getCode());
            audit.setDescription("废除合规评价提交审批");
            audit.setState(1);
            audit.setTemplateKey(assessmentConformanceTemplateKey);
            audit.setBusinessIds(new Gson().toJson(idList));
            Map<String, Object> businessMap = new HashMap<>();
            StringBuilder codes = new StringBuilder();
            for (String code : approverCodeList) {
                codes.append("1-").append(code.split("_")[0]).append(",");
            }
            businessMap.put("approver", codes.toString().substring(0, codes.lastIndexOf(",")));
            if (!flowManagement.initFlow(user, audit, businessMap)) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("废除提交合规评价失败");
            } else {
                factory.close();
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("废除提交合规评价成功");
            }
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean<?> deleteDraft(String conformanceAssessmentId) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        SessionFactory factory = new SessionFactory();
        try {
            ConformanceAssessmentMapper mapper = factory.getMapper(ConformanceAssessmentMapper.class);
            if (StringUtils.isBlank(conformanceAssessmentId)) {
                msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
                return msg;
            }
            ConformanceAssessment assessment = mapper.selectByPrimaryKey(conformanceAssessmentId);
            if (assessment == null) {
                msg.setCode(BusinessCode.CONFORMANCE_ASSESSMENT_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.CONFORMANCE_ASSESSMENT_NOT_EXIST.getDescription());
                return msg;
            } else if (assessment.getState() != 5) {
                msg.setCode(BusinessCode.CONFORMANCE_CAN_NOT_DELETE.getCode());
                msg.setDescription(BusinessCode.CONFORMANCE_CAN_NOT_DELETE.getDescription());
                return msg;
            }
            mapper.deleteByPrimaryKey(conformanceAssessmentId);
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean<?> getConformanceHistoryListByIds(String businessIds) {
        MessageBean<List> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), List.class);
        try (SessionFactory factory = new SessionFactory()) {
//            ConformanceAssessmentMapper mapper = factory.getMapper(ConformanceAssessmentMapper.class);
            ConformanceAssessmentHistoryMapper historyMapper = factory.getMapper(ConformanceAssessmentHistoryMapper.class);
            if (StringUtils.isBlank(businessIds)) {
                msg.setCode(24000);
                msg.setDescription("业务id不能为空");
                return msg;
            }
            List<String> businessIdList = JSONObject.parseArray(businessIds, String.class);
            if (businessIdList != null && !businessIdList.isEmpty()) {
//                List<ConformanceAssessment> list = mapper.queryListByIds(businessIdList);
//                msg.setData(list);
                List<ConformanceAssessmentHistory> list = historyMapper.queryListByIds(businessIdList);
                msg.setData(list);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put(ConformanceServiceImpl.class.getName(), this);
        map.put(ConformanceAuditService.class.getName(), new ConformanceAuditService());
    }

    @Override
    public void editApproval(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (idList != null && !idList.isEmpty()) {
                ConformanceAssessmentHistoryMapper historyMapper = factory.getMapper(ConformanceAssessmentHistoryMapper.class);
                ConformanceAssessmentMapper mapper = factory.getMapper(ConformanceAssessmentMapper.class);
                for (String id : idList) {
                    if (StringUtils.isNotBlank(id)) {
                        ConformanceAssessmentHistory history = historyMapper.selectByPrimaryKey(id);
                        if (history != null) {
                            ConformanceAssessment conformanceAssessment = translate(history);
                            //这里未保存历史记录 仅保存了审批记录
                            //若需要生成历史记录需要新建历史,不能直接覆盖原审批记录,否则 审批流程查看时数据会变
                            conformanceAssessment.setId(history.getOldId());
                            conformanceAssessment.setState(0);
                            mapper.updateByPrimaryKeySelective(conformanceAssessment);
                            history.setState(0);
                            history.setHistoryFlag(0);
                            historyMapper.updateByPrimaryKeySelective(history);
                        }
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    private void editApprovalDiscard(List<String> idList) {
        SessionFactory factory = new SessionFactory();
        try {
            if (idList != null && !idList.isEmpty()) {
                ConformanceAssessmentHistoryMapper historyMapper = factory.getMapper(ConformanceAssessmentHistoryMapper.class);
                ConformanceAssessmentMapper mapper = factory.getMapper(ConformanceAssessmentMapper.class);
                for (String id : idList) {
                    if (StringUtils.isNotBlank(id)) {
                        ConformanceAssessmentHistory history = historyMapper.selectByPrimaryKey(id);
                        if (history != null) {
                            ConformanceAssessment conformanceAssessment = mapper.selectByPrimaryKey(history.getOldId());
                            if (conformanceAssessment != null) {
                                conformanceAssessment.setState(0);
                                mapper.updateByPrimaryKeySelective(conformanceAssessment);
                            }
                            history.setState(4);
                            history.setHistoryFlag(0);
                            historyMapper.updateByPrimaryKeySelective(history);
                        }
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public void discardApproval(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (idList != null && !idList.isEmpty()) {
                ConformanceAssessmentHistoryMapper historyMapper = factory.getMapper(ConformanceAssessmentHistoryMapper.class);
                ConformanceAssessmentMapper mapper = factory.getMapper(ConformanceAssessmentMapper.class);
                for (String id : idList) {
                    if (StringUtils.isNotBlank(id)) {
                        ConformanceAssessmentHistory history = historyMapper.selectByPrimaryKey(id);
                        if (history != null) {
                            //这里只当作审批记录 若需要历史记录只需将将历史状态改为1即可
                            history.setState(2);
                            history.setHistoryFlag(0);
                            historyMapper.updateByPrimaryKeySelective(history);
                            mapper.deleteByPrimaryKey(history.getOldId());
                        }
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    public void discardApprovalDiscard(List<String> idList) {
        SessionFactory factory = new SessionFactory();
        try {
            if (idList != null && !idList.isEmpty()) {
                ConformanceAssessmentHistoryMapper historyMapper = factory.getMapper(ConformanceAssessmentHistoryMapper.class);
                ConformanceAssessmentMapper mapper = factory.getMapper(ConformanceAssessmentMapper.class);
                for (String id : idList) {
                    if (StringUtils.isNotBlank(id)) {
                        ConformanceAssessmentHistory history = historyMapper.selectByPrimaryKey(id);
                        if (history != null) {
                            //这里只当作审批记录 若需要历史记录只需将将历史状态改为1即可
                            history.setState(4);
                            history.setHistoryFlag(0);
                            historyMapper.updateByPrimaryKeySelective(history);
                            ConformanceAssessment conformanceAssessment = mapper.selectByPrimaryKey(history.getOldId());
                            if (conformanceAssessment != null) {
                                conformanceAssessment.setState(0);
                                mapper.updateByPrimaryKeySelective(conformanceAssessment);
                            }
                        }
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public void processDiscard(Audit audit) {
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (audit.getOperation() == 1) {
                editApprovalDiscard(idList);
            } else if (audit.getOperation() == 2) {
                discardApprovalDiscard(idList);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    private static ConformanceAssessment translate(ConformanceAssessmentHistory history) {
        ConformanceAssessment assessment = new ConformanceAssessment();
        assessment.setCorpCode(history.getCorpCode());
        assessment.setConformanceYear(history.getConformanceYear());
        assessment.setInstitutionId(history.getInstitutionId());
        assessment.setInstitutionCode(history.getInstitutionCode());
        assessment.setInstitutionFileCode(history.getInstitutionFileCode());
        assessment.setInstitutionFileName(history.getInstitutionFileName());
        assessment.setPublicationDate(history.getPublicationDate());
        assessment.setExecutionDate(history.getExecutionDate());
        assessment.setApplicableProvisions(history.getApplicableProvisions());
        assessment.setRemark(history.getRemark());
        assessment.setVersion(history.getVersion());
        assessment.setAttachment(history.getAttachment());
        assessment.setConformanceFlag(history.getConformanceFlag());
        assessment.setSuitDept(history.getSuitDept());
        assessment.setAddUser(history.getAddUser());
        assessment.setUpdateUser(history.getUpdateUser());
        assessment.setAddTime(history.getAddTime());
        assessment.setUpdateTime(history.getUpdateTime());
        assessment.setAddUserName(history.getAddUserName());
        assessment.setUpdateUserName(history.getUpdateUserName());
        return assessment;
    }



    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
